<!DOCTYPE html>
<html lang="en">

<head>
	<meta charset="UTF-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<meta name="viewport" content="width=device-width, initial-scale=1.0">
	<title>requestAnimationFrame_yyds</title>
	<style>
		body {
			box-sizing: border-box;
			background-color: #ccc;
		}

		.box1,
		.box2 {
			position: absolute;
			width: 160px;
			height: 160px;
			line-height: 160px;
			text-align: center;
			color: #fff;
			font-size: 13px;
		}

		.box1 {
			top: 40px;
			background: red;
		}

		.box2 {
			top: 210px;
			background: green;
		}
	</style>
	</style>
</head>

<body>
	<button class="btn">👉 let's go!</button>
	<div class="box1">定时器动画</div>
	<div class="box2">请求动画帧</div>
	<script>
		// 动画思路：不断修改dom元素的left值，使其运动起来（动画）
		let box1 = document.querySelector('.box1')
		let box2 = document.querySelector('.box2')

		// setInterval定时器方式 间隔17ms执行一次
		function setIntervalFn() {
			let timer = null
			box1.style.left = '0px'
			timer = setInterval(() => {
				let leftVal = parseInt(box1.style.left)
				if (leftVal >= 720) {
					clearInterval(timer)
				} else {
					box1.style.left = leftVal + 1 + 'px'
				}
			}, 17)
		}

		// requestAnimationFrame请求动画帧方式
		  //使用requestAnimationFrame
          
  let myBoxLeft = 0;
  const animation = () => {
    myBoxLeft+=1;
    box2.style.left = myBoxLeft + 'px';
    if(myBoxLeft<=720) {
      // setTimeout(animation,16.6);
      requestAnimationFrame(animation);
    }
  }
 

		// 动画绑定
		let btn = document.querySelector('.btn')
		btn.addEventListener('click', () => {
			setIntervalFn()
            animation()()
		})
	</script>
</body>

</html>
